package org.elfen.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;

import org.elfen.common.base.BaseController;
import org.elfen.common.result.ResultUtil;
import org.elfen.common.security.SecurityUtil;
import org.elfen.common.util.DataUtil;
import org.elfen.common.util.PageUtil;
import org.elfen.sys.entity.SysUser;
import org.elfen.sys.facade.SysUserBiz;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.baomidou.mybatisplus.plugins.Page;

/**
 * 用户管理控制器:POST来实现“增改”，GET来实现“删查”
 * 
 */
@RestController
@Api(value = "用户服务接口")
@RequestMapping(value = "/sysUser")
public class SysUserController extends BaseController{
	@Autowired
	private SysUserBiz sysUserService;
	
	@ApiOperation(value = "修改用户信息")
	@ApiImplicitParam(name="authorization",value="header中的token数据",required=true,paramType="header",dataType="String")
	@PostMapping(value="/update")
	public Object update(
			@ApiParam(value="用户信息的json（必须指定用户ID），其中：账户、密码、创建人、创建时间的信息不可修改",required=true)
			@RequestBody SysUser param) {
		if(DataUtil.isEmpty(param) || DataUtil.isEmpty(param.getId())){
			return ResultUtil.renderError("[修改用户信息]:用户ID不能为空！");
		}
		
		SysUser s = sysUserService.selectUserById(param.getId());
		if(DataUtil.isEmpty(s)){
			return ResultUtil.renderError("用户ID["+param.getId()+"]的用户不存在，请校验！");
		}
		//不更新的字段
		param.setUserPassword(null);
		param.setUserName(null);
		param.setCreateBy(null);
		param.setCreateTime(null);
		param.setIsDelete(null);
		
		Integer isEnable = param.getIsEnable();
		if(DataUtil.isNotEmpty(isEnable)){
			if(!DataUtil.pattern("^[0|1]$", isEnable+"")){
				return ResultUtil.renderSuccess("‘是否启用’字段值只能是0或1（0-启用，1-禁用）！");
			}
		}
		
		if(DataUtil.isNotEmpty(param.getUserNick())){
			SysUser s1 = sysUserService.selectUserByNick(param.getUserNick());
			if(DataUtil.isNotEmpty(s1)){
				return ResultUtil.renderError("昵称["+param.getUserNick()+"]已经被使用了！");
			}
		}
		
		if(DataUtil.isNotEmpty(param.getUserQQ())){
			SysUser s1 = sysUserService.selectUserByQQ(param.getUserQQ());
			if(DataUtil.isNotEmpty(s1)){
				return ResultUtil.renderError("UserQQ号["+param.getUserQQ()+"]已经被绑定了！");
			}
		}
		if(DataUtil.isNotEmpty(param.getTaobao())){
			SysUser s1 = sysUserService.selectUserByTabao(param.getTaobao());
			if(DataUtil.isNotEmpty(s1)){
				return ResultUtil.renderError("淘宝账号["+param.getTaobao()+"]已经被绑定了！");
			}
		}
		
		sysUserService.updaterById(param);
		return ResultUtil.renderSuccess("用户信息更新成功！");
	}

	// 用户详细信息
	@ApiOperation(value = "用户详细信息")
	@ApiImplicitParam(name="authorization",value="header中的token数据",required=true,paramType="header",dataType="String")
	@GetMapping(value = "/read/detail")
	public Object get(
			@ApiParam(value="要查看的用户ID",required=true)
			@RequestParam Long id) {
		if(DataUtil.isEmpty(id)){
			return ResultUtil.renderError("[用户详细信息]:用户ID不能为空！");
		}
		
		SysUser su = sysUserService.selectUserById(id);
		System.out.println(su.getId());
		
		return ResultUtil.renderSuccess(su);
	}

	@ApiOperation(value = "删除用户")
	@ApiImplicitParam(name="authorization",value="header中的token数据",required=true,paramType="header",dataType="String")
	@GetMapping(value="/delete")
	public Object delete(
			@ApiParam(value="要删除的用户ID",required=true)
			@RequestParam Long id) {
		if(DataUtil.isEmpty(id)){
			return ResultUtil.renderError("[删除用户信息]:用户ID不能为空！");
		}
		
		SysUser oldUser = sysUserService.selectUserById(id);
		if(DataUtil.isEmpty(oldUser) || DataUtil.isEmpty(oldUser.getUserName())){
			return ResultUtil.renderError("不存在该用户，无法执行删除操作！");
		}
		if(oldUser.getIsDelete()==1){
			return ResultUtil.renderError("该用户已经被删除，无需再执行删除操作！");
		}
		
		if(sysUserService.deleteById(oldUser.getId(),true)){
			return ResultUtil.renderSuccess("用户信息删除成功！");
		}
		return ResultUtil.renderError("用户信息删除失败！");
	}

	// 当前用户
	@ApiOperation(value = "当前用户信息")
	@ApiImplicitParam(name="authorization",value="header中的token数据",required=true,paramType="header",dataType="String")
	@GetMapping(value = "/read/current")
	public Object current() {
		SysUser su = sysUserService.selectUserById(getCurrUser());
		
		return ResultUtil.renderSuccess(su);
	}

	@ApiOperation(value = "修改当前用户信息")
	@PostMapping(value = "/update/person")
	public Object updatePerson(
			@ApiParam(value="个人信息的json【只需填写需要修改的字段的信息】，其中：个人账户、密码、创建人、创建时间的信息不可修改",required=true)
			@RequestBody SysUser param) {
		param.setId(getCurrUser());
		param.setUserPassword(null);
		param.setUserName(null);
		param.setCreateBy(null);
		param.setCreateTime(null);
		param.setIsDelete(null);
		
		Integer isEnable = param.getIsEnable();
		if(DataUtil.isNotEmpty(isEnable)){
			if(!DataUtil.pattern("^[0|1]$", isEnable+"")){
				return ResultUtil.renderSuccess("‘是否启用’字段值只能是0或1（0-启用，1-禁用）！");
			}
		}
		
		SysUser oldUser = sysUserService.selectUserById(getCurrUser());
		if(DataUtil.isNotEmpty(param.getUserNick()) && !param.getUserNick().equals(oldUser.getUserNick())){
			SysUser s1 = sysUserService.selectUserByNick(param.getUserNick());
			if(DataUtil.isNotEmpty(s1)){
				return ResultUtil.renderError("昵称["+param.getUserNick()+"]已经被使用了！");
			}
		}
		
		if(DataUtil.isNotEmpty(param.getUserQQ()) && !param.getUserQQ().equals(oldUser.getUserQQ())){
			SysUser s1 = sysUserService.selectUserByQQ(param.getUserQQ());
			if(DataUtil.isNotEmpty(s1)){
				return ResultUtil.renderError("QQ号["+param.getUserQQ()+"]已经被绑定了！");
			}
		}
		if(DataUtil.isNotEmpty(param.getTaobao()) && !param.getTaobao().equals(oldUser.getTaobao())){
			SysUser s1 = sysUserService.selectUserByTabao(param.getTaobao());
			if(DataUtil.isNotEmpty(s1)){
				return ResultUtil.renderError("淘宝账号["+param.getTaobao()+"]已经被绑定了！");
			}
		}
		
		sysUserService.updaterById(param);
		return ResultUtil.renderSuccess("用户信息更新成功！");
	}

	// 查询用户
	@ApiOperation(value = "查询用户")
	@ApiImplicitParam(name="authorization",value="header中的token数据",required=true,paramType="header",dataType="String")
	@PostMapping(value = "/read/list")
	public Object query(
			@ApiParam(value="当前页，比如：1",required=true,defaultValue="1")@RequestParam Integer pageNum, 
			@ApiParam(value="每页大小，比如：10",required=true,defaultValue="10")@RequestParam Integer pageSize, 
			@ApiParam(value="排序字段，比如:tid",required=true,defaultValue="tid")@RequestParam String orderBy, 
			@ApiParam(value="是否正排序,比如：false",required=true)@RequestParam boolean isAsc, 
			@ApiParam(value="查询条件信息",required=false)@RequestBody(required=false) SysUser user) {
		
		Page<SysUser> page = PageUtil.getPage(pageNum,pageSize,orderBy,isAsc); 
		
		Page<SysUser> resultPage = sysUserService.selectPage(page, user);
		
		return ResultUtil.renderSuccess(resultPage);
	}

	// 修改密码
	@ApiOperation(value = "修改当前用户的密码")
	@ApiImplicitParam(name="authorization",value="header中的token数据",required=true,paramType="header",dataType="String")
	@PostMapping(value = "/update/password")
	public Object updatePassword(
			@ApiParam(value="当前用户的原密码",required=true) @RequestParam String oldUserPassword,
			@ApiParam(value="新密码（只能是数字或英文字符）",required=true) @RequestParam String newUserPassword) {
		if(DataUtil.isEmpty(oldUserPassword)){
			return ResultUtil.renderSuccess("[用户详细信息]:用户原密码不能为空！");
		}
		if(DataUtil.isEmpty(newUserPassword)){
			return ResultUtil.renderSuccess("[用户详细信息]:用户新密码不能为空！");
		}
		
		if(!DataUtil.pattern("^[a-zA-Z0-9]+$", newUserPassword)){
			return ResultUtil.renderSuccess("[用户详细信息]:用户新密码只能包含数字或者英文！");
		}
		Long userId = getCurrUser();
		SysUser su = sysUserService.selectUserById(userId);
		String encryptPassword = SecurityUtil.encryptPassword(oldUserPassword);
		if(!encryptPassword.equals(su.getUserPassword())){
			return ResultUtil.renderSuccess("[用户详细信息]:用户原密码不正确！");
		}
		
		SysUser newUser = new SysUser();
		newUser.setId(userId);
		newUser.setUserPassword(SecurityUtil.encryptPassword(newUserPassword));
		sysUserService.updaterById(newUser);
		
		return ResultUtil.renderSuccess("用户密码修改成功！");
	}
}
